package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@Transactional
@RequestMapping("/employees")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo){
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("departments",departmentService.listAll());
        model.addAttribute("pageInfo",pageInfo);
        return "/employee/list";
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public JsonResult delete(@PathVariable("id") Long id){
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.deleteByPrimaryKey(id);
            jsonResult.setMsg("陈宫");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setMsg("失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    @GetMapping("/{id}")
    public String input(Model model ,@PathVariable("id")Long id){
        if (id == 0){
            return "/employee/save";
        }else{
            Employee employee = employeeService.selectByPrimaryKey(id);
            model.addAttribute("employee",employee);
            return "/employee/update";
        }
    }

    @PutMapping
    @ResponseBody
    public JsonResult update(Employee employee){
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.update(employee);
            jsonResult.setMsg("陈宫");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setMsg("失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    @PostMapping
    public String save(Employee employee){
            employeeService.insert(employee);
        return "redirect:/employees";
    }
}
